<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>插件加载测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .test-section {
            background: white;
            padding: 20px;
            margin: 10px 0;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .status {
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            font-weight: bold;
        }
        .success { background-color: #d4edda; color: #155724; }
        .error { background-color: #f8d7da; color: #721c24; }
        .warning { background-color: #fff3cd; color: #856404; }
        .info { background-color: #d1ecf1; color: #0c5460; }
        button {
            background-color: #007bff;
            color: white;
            border: none;
            padding: 10px 20px;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
        }
        button:hover {
            background-color: #0056b3;
        }
        #log {
            background-color: #f8f9fa;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 10px;
            max-height: 400px;
            overflow-y: auto;
            font-family: monospace;
            font-size: 12px;
        }
        .log-entry {
            margin: 2px 0;
            padding: 2px 0;
        }
    </style>
</head>
<body>
    <h1>抖音视频下载器 - 插件测试</h1>
    
    <div class="test-section">
        <h2>插件状态检查</h2>
        <div id="extensionStatus" class="status info">检查中...</div>
        <button onclick="checkExtensionStatus()">重新检查插件状态</button>
    </div>

    <div class="test-section">
        <h2>权限检查</h2>
        <div id="permissionStatus" class="status info">检查中...</div>
        <button onclick="checkPermissions()">检查权限</button>
    </div>

    <div class="test-section">
        <h2>Background Script 通信测试</h2>
        <div id="backgroundStatus" class="status info">未测试</div>
        <button onclick="testBackgroundScript()">测试 Background Script</button>
    </div>

    <div class="test-section">
        <h2>测试日志</h2>
        <button onclick="clearLog()">清空日志</button>
        <button onclick="exportLog()">导出日志</button>
        <div id="log"></div>
    </div>

    <script>
        function log(message, type = 'info') {
            const logDiv = document.getElementById('log');
            const timestamp = new Date().toLocaleTimeString();
            const logEntry = document.createElement('div');
            logEntry.className = `log-entry log-${type}`;
            logEntry.textContent = `[${timestamp}] ${message}`;
            logDiv.appendChild(logEntry);
            logDiv.scrollTop = logDiv.scrollHeight;
            console.log(`[${type.toUpperCase()}] ${message}`);
        }

        function updateStatus(elementId, message, type) {
            const element = document.getElementById(elementId);
            element.textContent = message;
            element.className = `status ${type}`;
        }

        async function checkExtensionStatus() {
            log('开始检查插件状态...', 'info');
            
            try {
                // 检查chrome.runtime是否可用
                if (typeof chrome === 'undefined' || !chrome.runtime) {
                    throw new Error('Chrome扩展API不可用');
                }

                // 获取插件信息
                const manifest = chrome.runtime.getManifest();
                updateStatus('extensionStatus', `✅ 插件已加载: ${manifest.name} v${manifest.version}`, 'success');
                log(`插件已加载: ${manifest.name} v${manifest.version}`, 'success');
                log(`权限: ${JSON.stringify(manifest.permissions)}`, 'info');
                
            } catch (error) {
                updateStatus('extensionStatus', `❌ 插件加载失败: ${error.message}`, 'error');
                log(`插件加载失败: ${error.message}`, 'error');
            }
        }

        async function checkPermissions() {
            log('开始检查权限...', 'info');
            
            const requiredPermissions = ['downloads', 'webRequest', 'scripting', 'activeTab', 'storage', 'tabs'];
            let allPermissionsGranted = true;
            
            for (const permission of requiredPermissions) {
                try {
                    const hasPermission = await chrome.permissions.contains({permissions: [permission]});
                    log(`权限 ${permission}: ${hasPermission ? '✅' : '❌'}`, hasPermission ? 'success' : 'error');
                    if (!hasPermission) allPermissionsGranted = false;
                } catch (error) {
                    log(`检查权限 ${permission} 失败: ${error.message}`, 'error');
                    allPermissionsGranted = false;
                }
            }
            
            updateStatus('permissionStatus', 
                allPermissionsGranted ? '✅ 所有权限已授予' : '❌ 部分权限缺失', 
                allPermissionsGranted ? 'success' : 'error'
            );
        }

        async function testBackgroundScript() {
            log('开始测试Background Script通信...', 'info');
            
            try {
                const response = await chrome.runtime.sendMessage({ type: 'GET_VIDEO_URLS' });
                log(`Background Script响应: ${JSON.stringify(response)}`, 'success');
                updateStatus('backgroundStatus', '✅ Background Script 通信正常', 'success');
            } catch (error) {
                log(`Background Script通信失败: ${error.message}`, 'error');
                updateStatus('backgroundStatus', `❌ Background Script 通信失败: ${error.message}`, 'error');
            }
        }

        function clearLog() {
            document.getElementById('log').innerHTML = '';
        }

        function exportLog() {
            const logContent = document.getElementById('log').textContent;
            const blob = new Blob([logContent], { type: 'text/plain' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `extension-test-log-${new Date().toISOString().slice(0,19).replace(/:/g,'-')}.txt`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        }

        // 页面加载完成后自动检查
        window.addEventListener('load', () => {
            log('页面加载完成，开始自动检查...', 'info');
            setTimeout(() => {
                checkExtensionStatus();
                setTimeout(() => {
                    checkPermissions();
                    setTimeout(() => {
                        testBackgroundScript();
                    }, 1000);
                }, 1000);
            }, 500);
        });

        // 监听来自插件的消息
        if (typeof chrome !== 'undefined' && chrome.runtime) {
            chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
                log(`收到插件消息: ${JSON.stringify(message)}`, 'info');
                return true;
            });
        }
    </script>
</body>
</html>